import type { RouteRecordRaw } from "vue-router";
import type { MenuItem } from "@/store/user.ts";

// @ts-ignore
const modules = import.meta.glob("/src/views/**/*.vue");

export function buildRoutesFromMenus(menus: MenuItem[], parentTitle = ""): RouteRecordRaw[] {
  const result: RouteRecordRaw[] = [];
  const travel = (items: MenuItem[],parent: string) => {
    items.forEach(item => {
      if (item.child && item.child.length) {
        travel(item.child,item.menuName);
      }
      if (item.menuUrl) {
        const normalizedPath = item.menuUrl.replace(/^\//, "").split("?")[0];
        const filePath = `/src/views/${normalizedPath}.vue`;
        result.push({
          path: item.menuUrl,
          name: item.menuCode || item.menuUrl,
          meta: {
            title: item.menuName,
            icon: "Menu",
            parentTitle: parent || "",
            url: item.menuUrl
          },
          component: modules[filePath]
              ? modules[filePath]
              : modules["/src/views/NotFound.vue"]
        });
      }
    });
  };

  travel(menus,parentTitle);
  return result;
}
